//
//  ShakeAward.m
//  gee
//
//  Created by Apple on 11-5-21.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "ShakeAward.h"


@implementation ShakeAward
@synthesize motionManager;
@synthesize label;;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    award_count = 0;
    label.text = @"请先摇晃";
    
    self.motionManager = [[[CMMotionManager alloc] init] autorelease];
    motionManager.accelerometerUpdateInterval = kUpdateInterval;
    NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    
    [motionManager startAccelerometerUpdatesToQueue:queue
                                        withHandler:
     ^(CMAccelerometerData *accelerometerData, NSError *error){
		 if (error) {
			 [motionManager stopAccelerometerUpdates];
		 } else {
			 if (!is_award) {
				 CMAcceleration acceleration = accelerometerData.acceleration;
				 if (acceleration.x > kAccelerationThreshold
					 || acceleration.y > kAccelerationThreshold
					 || acceleration.z > kAccelerationThreshold) 
                 {
					 [self performSelectorOnMainThread:@selector(you_are_award:) 
												 withObject:nil 
											  waitUntilDone:NO];
    
					 is_award = NO;
				 }
			 }
		 }
	 }];

    [super viewDidLoad];

}

- (void)you_are_award:(NSString *)nsstr{
    
    
    award_count++;

    label.text      =       [@"摇晃超过250次会有神秘礼物等着您 一共摇晃 了 " stringByAppendingFormat:@" 第 %d 次 ",award_count];
    NSLog(@"%@",label.text );
    
    if (award_count >= 80){
        
        label.text =  [label.text stringByAppendingFormat:@"\n %@ ",@"恭喜您中了头号大奖"];
        
    }
    
}
- (void)viewDidUnload
{
    self.motionManager = nil;
    self.label = nil;

    [super viewDidUnload];
}
- (void)dealloc
{

    [label release];
    [motionManager release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [label setText:@""];
    is_award = NO;
}

@end
